package com.nuoyuan.wx.admin.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nuoyuan.wx.common.config.OssConfig;
import com.nuoyuan.wx.common.constant.OssFileDirEnum;
import com.nuoyuan.wx.common.controller.BaseController;
import com.nuoyuan.wx.common.utils.DateUtil;
import com.nuoyuan.wx.common.utils.OssClientUtil;
import com.nuoyuan.wx.vo.FileVo;
import com.nuoyuan.wx.vo.NoticeVo;
import com.nuoyuan.wx.vo.QueryNoticeVo;
import com.nuoyuan.wx.vo.PageVo;
import com.nuoyuan.wx.common.utils.GsonUtil;
import com.nuoyuan.wx.dao.mapper.NoticeMapper;
import com.nuoyuan.wx.dao.po.NoticePo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package com.nuoyuan.wx.admin.controller
 * @ClassName NoticeController
 * @Description TODO
 * @Author linus
 * @Date 2020-02-21 15:42
 * @Version 1.0
 **/
@RestController("AdminNoticeController")
public class NoticeController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(NoticeController.class);

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private OssConfig ossConfig;

    @RequestMapping(value = "/admin/notices", method = RequestMethod.GET)
    @ResponseBody
    public String list(PageVo page, HttpServletRequest request, HttpServletResponse response) {
        try {
            Wrapper<NoticePo> queryWrapper = new QueryWrapper<>();
            ((QueryWrapper<NoticePo>) queryWrapper).eq("is_deleted", false).orderByDesc("order_date");
            IPage p = new Page();
            p.setCurrent(page.getPageNo());
            p.setSize(page.getPageSize());
            IPage<NoticePo> pages = noticeMapper.selectPage(p, queryWrapper);
            if (pages == null || CollectionUtils.isEmpty(pages.getRecords())) {
                PageVo emptyP = new PageVo<>();
                emptyP.setItems(new ArrayList());
                return GsonUtil.toJson(emptyP);
            }

            List<NoticePo> pos = pages.getRecords();
            List<NoticeVo> vos = new ArrayList<>();
            for(NoticePo po : pos) {
                NoticeVo vo = new NoticeVo();
                BeanUtils.copyProperties(po, vo);
                vo.setCreateTime(DateUtil.formatDate(po.getCreateTime(), DateUtil.FMT_DATE_YYYYMMDD_HHMMSS));
                vos.add(vo);
            }
            page.setItems(vos);
            page.setCount(pages.getTotal());
            return GsonUtil.toJson(page);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
    }


    /**
     * 详情
     *
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/notice", method = RequestMethod.GET)
    @ResponseBody
    public String detail(NoticePo param, HttpServletRequest request, HttpServletResponse response) {
        try {
            Wrapper<NoticePo> updateWrapper = new UpdateWrapper<>();
            ((UpdateWrapper<NoticePo>) updateWrapper).eq("notice_id", param.getNoticeId());
            NoticePo po = noticeMapper.selectOne(updateWrapper);
            return GsonUtil.toJson(po);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
    }


    /**
     * 新增
     *
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/notice", method = RequestMethod.POST)
    @ResponseBody
    public String add(@RequestBody NoticePo param, HttpServletRequest request, HttpServletResponse response) {
        try {
            noticeMapper.insert(param);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
        return this.buildSimpleSuccResp();
    }

    /**
     * 改变顺序
     *
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/notice/order", method = RequestMethod.POST)
    @ResponseBody
    public String changeOrder(@RequestBody QueryNoticeVo param, HttpServletRequest request, HttpServletResponse response) {
        try {
            Wrapper<NoticePo> upQueryWrapper = new QueryWrapper<>();
            ((QueryWrapper<NoticePo>) upQueryWrapper).eq("notice_id", param.getUpNoticeId());
            NoticePo upNotice = noticeMapper.selectOne(upQueryWrapper);


            Wrapper<NoticePo> downQueryWrapper = new QueryWrapper<>();
            ((QueryWrapper<NoticePo>) downQueryWrapper).eq("notice_id", param.getDownNoticeId());
            NoticePo downNotice = noticeMapper.selectOne(downQueryWrapper);

            downNotice.setOrderDate(upNotice.getCreateTime());
            upNotice.setOrderDate(downNotice.getCreateTime());


            Wrapper<NoticePo> upUpdateWrapper = new UpdateWrapper<>();
            ((UpdateWrapper<NoticePo>) upUpdateWrapper).eq("notice_id", param.getUpNoticeId());
            noticeMapper.update(upNotice, upUpdateWrapper);


            Wrapper<NoticePo> downUpdateWrapper = new UpdateWrapper<>();
            ((UpdateWrapper<NoticePo>) downUpdateWrapper).eq("notice_id", param.getDownNoticeId());
            noticeMapper.update(downNotice, downUpdateWrapper);

        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
        return this.buildSimpleSuccResp();
    }

    /**
     * 更新
     *
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/updateNotice", method = RequestMethod.POST)
    @ResponseBody
    public String update(@RequestBody NoticePo param, HttpServletRequest request, HttpServletResponse response) {
        try {
            Wrapper<NoticePo> updateWrapper = new UpdateWrapper<>();
            ((UpdateWrapper<NoticePo>) updateWrapper).eq("notice_id", param.getNoticeId());
            noticeMapper.update(param, updateWrapper);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
        return this.buildSimpleSuccResp();
    }


    /**
     * 删除
     *
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/delNotice", method = RequestMethod.POST)
    @ResponseBody
    public String delete(@RequestBody NoticePo param, HttpServletRequest request, HttpServletResponse response) {
        try {
            param.setIsDeleted(true);
            Wrapper<NoticePo> updateWrapper = new UpdateWrapper<>();
            ((UpdateWrapper<NoticePo>) updateWrapper).eq("notice_id", param.getNoticeId());
            noticeMapper.update(param, updateWrapper);
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        }
        return this.buildSimpleSuccResp();
    }


    /**
     * 上传文件
     *
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin/notice/faceimg", method = RequestMethod.POST)
    @ResponseBody
    public String upload(FileVo param, HttpServletRequest request, HttpServletResponse response) {
        String fileUlr = OssClientUtil.upload(ossConfig, param.getFile(), OssFileDirEnum.NOTICE.name());
        param.setFileName(param.getFile().getOriginalFilename());
        param.setFileUrl(fileUlr);
        return GsonUtil.toJson(param);
    }
}
